package com.rui.proxy.model;

import com.rui.proxy.obj.TrainStation;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description: 代售点卖票（JDK动态代理类）
 * @Author: ZhangRui
 * @Date: 2023/3/2 15:36
 * @Version: 1.0
 */
public class DynamicProxyPoint implements InvocationHandler {

    private TrainStation trainStation;

    public TrainStation getProxyObject(TrainStation trainStation) {
        this.trainStation = trainStation;
        Class<? extends TrainStation> clazz = trainStation.getClass();
        return (TrainStation) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // 针对特定方法进行增强
        if (method.getName().equals("sellTickets")) {
            this.collectionCharge();
        }

        return method.invoke(this.trainStation, args);
    }

    /**
     * 代理类其他处理
     *
     * @return void
     * @author ZhangRui
     * @date 2023/3/2 15:26
     */
    private void collectionCharge() {
        System.out.println("代售加收5%手续费");
    }
}